package com.levi.juc.common_class;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量   用于限流
 * 一次只有这么多资源，其余的线程需要排队等待，达到限流到效果
 *
 *
 *  //获得令牌
 *      semaphore.acquire();
 * //释放令牌
 *      semaphore.release();
 */
public class SemaphoreTest {
    public static void main(String[] args) {
//        Semaphore semaphore = new Semaphore(3);
//        for (int i = 1; i < 7; i++) {
//            new Thread(()->{
//                try {
//                    //获得令牌
//                    semaphore.acquire();
//                    System.out.println(Thread.currentThread().getId()+"获得了令牌");
//                    TimeUnit.SECONDS.sleep(2);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }finally {
//                    //释放令牌
//                    semaphore.release();
//                    System.out.println(Thread.currentThread().getId()+"释放了令牌");
//                }
//            }).start();
//        }

        Semaphore semaphore1 = new Semaphore(3);
        for (int i = 0; i < 8; i++) {
            new Thread(()->{
                try {
//                    semaphore1.acquire();
                    //等待2秒，如果没有获取到令牌就放弃
                    boolean result = semaphore1.tryAcquire(2, TimeUnit.SECONDS);
                    if (result) {
                        System.out.println(Thread.currentThread().getName() + "获得了令牌");
                    }
                    //一个令牌使用2秒钟
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore1.release();
                    System.out.println(Thread.currentThread().getName()+"释放了令牌");
                }
            }).start();
        }

        Semaphore semaphore3 = new Semaphore(2);
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    boolean res = semaphore3.tryAcquire(2, TimeUnit.SECONDS);
                    if (res) {
                        System.out.println(Thread.currentThread().getName()+"拿到了一个信号33333");
                        TimeUnit.SECONDS.sleep(2);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore3.release();
                    System.out.println(Thread.currentThread().getName()+"释放了一个信号33333");
                }
            }).start();

        }
    }


}
